<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search ref="customSearchRef" v-slot="{ params }" :default-params="{ adCode: [] }" @submit="handleInitTable">
      <t-col :span="3">
        <t-form-item label="楼盘名称" name="name">
          <t-input v-model:value="params.name" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="详细地址" name="address">
          <t-input v-model:value="params.address" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="归属城市" name="adCode">
          <t-cascader
            v-model:value="params.adCode"
            :options="city.tree"
            :keys="{ label: 'name', value: 'adcode', children: 'districts' }"
            placeholder=""
            filterable
            clearable
            check-strictly
            value-type="full"
            @change="(value: any) => handleAdCodeChange(value, params)"
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="创建时间" name="createTime">
          <t-date-range-picker
            allow-input
            v-model:value="params.createTime"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
          />
        </t-form-item>
      </t-col>
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table
      ref="customTableRef"
      row-key="id"
      :columns="columns"
      :api="propertyManageCRUD.page"
      column-controller-key="propertyManageList"
    >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <t-button v-permission="['system:property-info:create']" @click="handleOpenDialog('create', { adCode: [] })">
            新建楼盘
          </t-button>
        </div>
      </template>
      <template #adCode="{ row }">
        {{ analysisCity(row) }}
      </template>
      <template #createTime="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <t-link
            v-permission="['system:property-info:query']"
            theme="primary"
            @click="handleOpenDialog('read', { id: row.id })"
          >
            详情
          </t-link>
          <t-link
            v-permission="['system:property-info:update']"
            theme="primary"
            @click="handleOpenDialog('update', { id: row.id })"
          >
            编辑
          </t-link>
          <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
            <t-link v-permission="['system:property-info:delete']" theme="danger"> 删除 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </custom-table>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly, mode }"
      :api-map="propertyManageCRUD"
      header="*楼盘"
      :on-before-set-data="handleDialogSetData"
      @request-success="handleDialogRequestSuccess"
    >
      <t-form-item
        v-if="mode === 'create'"
        label="楼盘名称"
        name="propertyName"
        :rules="[{ required: true, message: '请选择楼盘名称' }]"
      >
        <t-select
          v-model:value="formData.propertyName"
          v-model:input-value="formData.inputValue"
          placeholder="请选择楼盘名称"
          clearable
          filterable
          :readonly="readonly"
          :loading="loadingPropertyName"
          @search="handleResetSearchPropertyName"
          @change="(value) => handleChangePropertyName(value, formData)"
        >
          <t-option v-for="_ in propertyList" :key="_.id" :value="_.id" :label="_.title">
            {{ _.title }}
            <span style="color: var(--td-text-color-secondary)">{{ _.address }}</span>
          </t-option>
          <template #panelBottomContent>
            <t-button
              v-show="pagination.count && pagination.count > propertyList.length"
              theme="primary"
              variant="text"
              block
              @click="handleSearchPropertyName(formData.inputValue)"
            >
              加载更多
            </t-button>
          </template>
        </t-select>
      </t-form-item>
      <t-form-item v-else label="楼盘名称" name="name" :rules="[{ required: true, message: '请输入楼盘名称' }]">
        <t-input v-model:value="formData.name" placeholder="请输入楼盘名称" clearable :readonly="readonly" />
      </t-form-item>
      <template v-if="formData.propertyName || mode !== 'create'">
        <t-form-item label="详细地址" name="address">
          <t-textarea v-model:value="formData.address" placeholder="请输入详细地址" :readonly="readonly" />
        </t-form-item>
        <t-form-item label="归属城市" name="adCode" :rules="[{ required: true, message: '请选择归属城市' }]">
          <t-cascader
            v-model:value="formData.adCode"
            :options="city.tree"
            :keys="{ label: 'name', value: 'adcode', children: 'districts' }"
            placeholder="请选择归属城市"
            filterable
            clearable
            :readonly="readonly"
            value-type="full"
            @change="(value: any) => handleAdCodeChange(value, formData)"
          />
        </t-form-item>
        <t-form-item label="经度" name="longitude" :rules="[{ required: true, message: '请输入经度' }]">
          <t-input-number
            v-model:value="formData.longitude"
            placeholder="请输入经度"
            clearable
            :readonly="readonly"
            theme="normal"
            style="width: 100%"
          />
        </t-form-item>
        <t-form-item label="纬度" name="latitude" :rules="[{ required: true, message: '请输入纬度' }]">
          <t-input-number
            v-model:value="formData.latitude"
            placeholder="请输入纬度"
            clearable
            :readonly="readonly"
            theme="normal"
            style="width: 100%"
          />
        </t-form-item>
      </template>
    </custom-dialog>
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'PropertyManage',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, SelectValue, TableCol } from 'tdesign-vue-next';
import { onMounted, reactive, ref, useTemplateRef } from 'vue';

import { propertyManageCRUD, searchPropertyListByKeyword } from '@/api/config/property';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import city from '@/utils/city';

// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'name', title: '楼盘名称', width: 200 },
  { colKey: 'address', title: '详细地址', width: 300 },
  { colKey: 'adCode', title: '归属城市', width: 250 },
  { colKey: 'longitude', title: '经度', width: 100 },
  { colKey: 'latitude', title: '纬度', width: 100 },
  { colKey: 'createTime', title: '创建时间', width: 180 },
  { colKey: 'operation', title: '操作', width: 150, fixed: 'right' },
];
// 处理初始化表格
const handleInitTable = () => {
  const params = { ...customSearchRef.value.params };
  if (!params.adCode || !params.adCode.length) {
    delete params.provinceCode;
    delete params.cityCode;
    delete params.areaCode;
  }
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(() => {
  handleInitTable();
});
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  propertyManageCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理归属城市改变
const handleAdCodeChange = (value: string[], params: Record<string, any>) => {
  params.provinceCode = value[0] || '';
  params.cityCode = value[1] || '';
  params.areaCode = value[2] || '';
};
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
  params.adCode = [params.provinceCode, params.cityCode, params.areaCode];
};
// 解析城市
const analysisCity = (row: Record<string, any>) => {
  let result = '';
  if (row.provinceCode) {
    result += city.list.find((item) => item.adcode === row.provinceCode).name;
  }
  if (row.cityCode) {
    result += ` / ${city.list.find((item) => item.adcode === row.cityCode).name}`;
  }
  if (row.areaCode) {
    result += ` / ${city.list.find((item) => item.adcode === row.areaCode).name}`;
  }
  return result;
};
// 加载楼盘名称
const loadingPropertyName = ref(false);
// 楼盘列表
const propertyList = ref([]);
// 分页
const pagination = reactive({
  pageIndex: 1,
  count: 0,
});
// 处理搜索楼盘名称
const handleSearchPropertyName = (keyword: string) => {
  if (!keyword) return;
  loadingPropertyName.value = true;
  const params = { keyword, pageIndex: pagination.pageIndex };
  searchPropertyListByKeyword(params)
    .then((data) => {
      data = JSON.parse(data);
      propertyList.value.push(...data.data);
      pagination.pageIndex++;
      pagination.count = data.count;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      loadingPropertyName.value = false;
    });
};
// 处理重置搜索楼盘名称
const handleResetSearchPropertyName = (keyword: string) => {
  propertyList.value = [];
  pagination.pageIndex = 1;
  pagination.count = 0;
  handleSearchPropertyName(keyword);
};
// 处理改变楼盘名称
const handleChangePropertyName = (value: SelectValue, formData: Record<string, any>) => {
  if (!value) return;
  const propertyInfo = propertyList.value.find((item) => item.id === value);
  formData.name = propertyInfo.title;
  formData.address = propertyInfo.address;
  formData.longitude = propertyInfo.location.lng;
  formData.latitude = propertyInfo.location.lat;
  formData.provinceCode = `${propertyInfo.adcode.toString().substring(0, 2)}0000`;
  formData.cityCode = `${propertyInfo.adcode.toString().substring(0, 4)}00`;
  formData.areaCode = propertyInfo.adcode.toString();
  formData.adCode = [formData.provinceCode, formData.cityCode, formData.areaCode];
};
</script>

<style lang="less" scoped></style>
